import json
import logging
import os

import pymongo

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")

class MongoOperator():
    def __init__(self):
        self.mongoClient = pymongo.MongoClient(
            "mongodb://fzxm:chenchen@121.37.202.206:27017/fzxm?authSource=admin&readPreference=primary&appname=MongoDB%20Compass&ssl=false")

        self.fzxmdb = self.mongoClient['fzxm']

    def insert(self, data):
        self.fzxmdb['fzxm_commondity'].insert_one(data);
        pass

    def __del__(self):
        self.mongoClient.close()

    def exportData(self):
        collection = self.fzxmdb['fzxm_commondity']
        rows = collection.find()
        list = []
        fp = open('dump.json', 'w+')
        for row in rows:
            fp.write(json.dumps(row, ensure_ascii=False))
        fp.close()
        pass

    def importCategory(self):
        basedir = "./storebase/merchant/productCategory"
        fp = open(basedir, 'r+')
        obj = json.load(fp);

        datas = obj['data']
        for data in datas:
            self.recrusive(data)

        fp.close()
        pass

    def recrusive(self, data):
        id = data['id']
        pid = data['pid']
        name = data['name']
        record = {'_id': id, 'pid': pid, 'name': name};
        self.fzxmdb['fzxm_type'].insert_one(record);
        children = data['children']
        if children != None:
            for child in children:
                self.recrusive(child)

    def parseForCategory(self):
        pids = self.queryAllSubPid()
        ##pid与ids进行绑定就好了
        for pid in pids:
            filename = "./storebase/merchant/product?pageSize=200&orderBy=&productCategoryId=%d&productName=&tag=&pageIndex=1" % (
                pid)
            fp=open(filename,'r+')
            dict=json.load(fp)
            records=dict['data']['records']
            if len(records) == 0:
               continue

            ids=list(map(lambda x:x['productId'],records))
            # for cid in ids:
            #     record = {'tid':pid,'cid':cid}
            #     self.fzxmdb['fzxm_commondity_type'].insert_one(record)
            self.fzxmdb['fzxm_commondity_type_ext'].insert_one({'tid':pid,'cids':ids})
            fp.close();

    pass

    def queryAllSubPid(self):
        res = self.fzxmdb['fzxm_type'].find({'pid': {'$not': {'$eq': 0}}})
        r = list(map(lambda x: x['_id'], res))
        return r;

    def importdata(self):
        basedir = "./storebase/merchant/product"
        filepath = "./storebase/merchant/product.json"
        productsfp = open(filepath, 'r+')
        productsmap = json.load(productsfp)
        records = productsmap['data']['records']
        for record in records:
            productId = record['productId']
            fp = open(os.path.join(basedir, '%s' % (productId)))
            map = json.load(fp)
            data = map['data']
            fp.close()
            data['name'] = record['name']
            data['price'] = record['price']
            data['tag'] = record['tag']
            data['_id'] = data['id']
            del data['id']

            print(json.dumps(data))
            # mop.insert(data)


if __name__ == "__main__":
    mop = MongoOperator()
    # mop.exportData()
    # mop.importdata()
    mop.importCategory();
    # mop.parseForCategory()
    # mop.queryAllSubPid();
